#!/usr/bin/env python
# coding:utf-8

"""
Created by ben on 2010/10/27 .
Copyright (c) 2010 http://sa3.org All rights reserved. 
"""
import re
import unicodedata
import Cookie
import os
import sys


def filter_url(s):
    '''
    url contains [a-z0-9-]
    can not startswith or endswith '-'
    '''
    if not isinstance(s,str):
        s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')
    return  re.sub(r'[^a-z0-9]+','-',s.lower()).strip('-')


def write_cookies(key, val, expired_time):
    cookies = Cookie.SimpleCookie()
    cookies[key] = val
    cookies[key]['path'] = '/'
    cookies[key]['max-age'] = expired_time
    output_headers = []
    output_headers.append('%s\r\n' % cookies)
    for header in output_headers:
        sys.stdout.write(header)

def read_cookies(key):
    cookies = os.environ.get('HTTP_COOKIE', None)
    if cookies is not None:
        user_cookie = Cookie.SimpleCookie()
        user_cookie.load(cookies)
        try:
            return user_cookie[key].value
        except KeyError:
            return None
    else:
        return None

if __name__=='__main__':
    pass